<template>
  <div class="video-page">
    <div class="terminal-search-title">
      <el-row :gutter="15">
        <el-col :span="3">
          <el-input
            placeholder="搜索资源名称"
            suffix-icon="el-search"
            @keyup.native.enter="queryMethods"
            v-model="searchObj.quicklyName">
          </el-input>
        </el-col>

        <el-col class="control-fixed-pos" :span="18">
          <el-button type="default" @click="sendFileBySelection">同步至终端</el-button>
          <el-button @click="startUploadFile" type="primary" icon="el-icon-plus">
            添加
          </el-button>
          <el-button type="danger" @click="mutiDelHandler" icon="el-icon-delete">删除</el-button>
        </el-col>
      </el-row>
    </div>

    <CommonTable
      class="commonTable"
      ref="quickOperateRef"
      :is-selection="true"
      :is-show-index="true"
      @changeRow="changeQickListRowMethods"
      :is-has-opera="true"
      :t-column-data="quickOperateCol"
      :remote-api="getQuickOperateList"
      :query-params="searchObj"
      :is-reserve-select="true"
      operating-width="180px"
    >
      <template slot="quickly_name" slot-scope="scope">
        <div class="file-name-row">
          <img src="./images/quickList.png" class="file-icon" alt="">
          <div>{{scope.row.quickly_name}}</div>
        </div>
      </template>
      <template slot="bind_client" slot-scope="scope">
        <div>
          {{getBindClient(scope.row)}}
        </div>
      </template>
      <template slot="operate" slot-scope="scope" class="operate-btn">
        <el-button type="text" @click="sendFile(scope.row)">分发</el-button>
        <el-button type="text" @click="editFile(scope.row)">编辑</el-button>
        <el-button type="text" class="del-button" @click="showDelWarn(scope.row)">删除</el-button>
      </template>
    </CommonTable>


    <el-dialog
      :title="['','选择内容', '选择终端'][step]"
      :visible.sync="isShowUploadDialog"
      width="60%"
      :before-close="handleClose">
      <div>
        <div class="steps">
          <el-steps :active="step - 1" finish-status="success" align-center>
            <el-step title="选择内容"></el-step>
            <el-step title="选择终端"></el-step>
          </el-steps>
        </div>
        <div v-show="step == 1">
          <el-form :inline="true" :model="searchMedia" class="demo-form-inline">
            <el-form-item label="素材类型">
              <el-select clearable @change="changeMediaType" v-model="searchMedia.type" placeholder="请选择">
                <el-option
                  v-for="item in mediaTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <TreeTable
            class="commonTable"
            ref="quickOperateContentRef"
            :is-selection="true"
            rowKey="id"
            :is-show-index="false"
            :is-has-opera="false"
            :t-column-data="quickOperateSelectContentCol"
            :remote-api="getFileList"
            :query-params="searchFileParams"
            :is-reserve-select="true"
            @changeRow="changeFileRowMethods"
            :selectedMediaIds="selectedMediaIds"
            :isShowUploadDialog="isShowUploadDialog"
            operating-width="180px"
          >
            <template slot="media_name" slot-scope="scope">
              <div class="file-name-row">
                <img :src="scope.row.file_type == 1 ? require('./images/folder.png') : getFileTypeImage(scope.row)" class="file-icon" alt="">
                <div>{{scope.row.media_name}}</div>
              </div>
            </template>
          </TreeTable>
<!--          <el-tree :data="treeData" :props="defaultProps" @node-click="handleNodeClick"></el-tree>-->

        </div>
        <div v-show="step == 2">
          <CommonTable
            class="commonTable"
            ref="terListTableRef"
            :is-selection="true"
            :is-show-index="false"
            :is-has-opera="false"
            :t-column-data="selectTerListCol"
            :remote-api="getTerList"
            :is-reserve-select="true"
            @changeRow="changeRowMethods"
            operating-width="180px"
          >
            <template slot="media_name" slot-scope="scope">
              <div class="file-name-row">
                <img :src="scope.row.image" class="file-icon" alt="">
                <div>{{scope.row.media_name}}</div>
              </div>
            </template>
          </CommonTable>
        </div>
        <div v-show="step == 3">
          <el-form label-width="100px">
            <el-form-item label="列表名称">
              <el-input type="text" v-model="operateName"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" v-if="step !== 1" @click="confirmSavePrevStep">上一步</el-button>
        <el-button type="primary" @click="confirmSaveStep">下一步</el-button>
      </span>
    </el-dialog>

    <WarnPanelDialog
      :statusProp="statusProp"
      @confirmHandler="confirmDelMethods"
      @cancelHandler="cancelHandler"
    ></WarnPanelDialog>

    <!--文件分发选择终端-->
<!--    <TerListDialog-->
<!--      :show-ter-dialog="showTerDialog"-->
<!--      @on-cancel="cancelTerDialog"-->
<!--      @on-confirm="confirmSelectTer"-->
<!--    ></TerListDialog>-->
  </div>
</template>

<script>
import CommonTable from "@/components/Table/commonTable";
import TreeTable from "@/views/distribute/component/treeTable";
import UploadDialog from "@/components/UploadFile/index"
import {quickOperateCol} from "@/views/distribute/tableCol/quickOperateCol";
import {selectTerListCol} from './tableCol/selectTerListCol'
import {quickOperateSelectContentCol} from './tableCol/quickOperateSelectContentCol'
import * as service from './service'
import * as terService from '../terminal/service'
import {getQuickOperateContentList, quicklyDel, quicklySave, quicklySend} from "./service";
import SendFileMixins from "@/views/distribute/mixins/sendFileMixins";
import {suffixFileMapStr} from '@/utils/config'


export default {
  name: "video",
  mixins: [SendFileMixins],
  components: {
    CommonTable,
    TreeTable,
    UploadDialog
  },
  data() {
    return {
      selectedMediaIds: [],
      mediaTypeOptions: [],
      showTerDialog: false,
      clickCache: {},
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      historySelection: [],
      statusProp: false,
      operateName: '',
      quickOperateSelectContentCol,
      getFileList: service.getFileList,
      getQuickOperateList: service.getQuickOperateList,
      getTerList: terService.getClientList,
      isShowUploadDialog: false,
      searchObj: {
        quicklyName: '',
        page: 1,
        pageSize: 20
      },
      step: 1,
      fileList: [],
      selectTerListCol,
      quickOperateCol,
      total: 0,
      mutiDelList: [],
      mutiTerList: [],
      mutiSelectFileList: [],
      searchFileParams: {
        name: '',
        parentId: 0,
        child: true,
        audit: 1
        // fileType: 2
      },
      searchMedia: {
        type: ''
      }
    }
  },
  computed: {
    getBindClient() {
      return (row) => {
        let clientListTmp = []
        if(row.client_name && row.client_name.indexOf(',') !== -1) {
          let clientNameList = row.client_name.split(',')
          clientNameList.forEach((item) => {
            if(clientListTmp.indexOf(item) === -1) {
              clientListTmp.push(item)
            }
          })
        } else {
          clientListTmp = [row.client_name]
        }

        return clientListTmp.join(',')
      }
    }
  },
  watch: {
    isShowUploadDialog(val) {
      if(val && this.step == 1) {
        this.$nextTick(() => {
          this.$refs.quickOperateContentRef.clearSelectionMethods()
          this.$refs.quickOperateContentRef.resetPageNo()
          this.getMediaList()
        })
      }
    },
    step(val) {
      if(val == 2) {
        this.$nextTick(() => {
          this.$refs.terListTableRef.clearSelectionMethods()
          const params = Object.assign({}, this.searchFileParams)
          this.$refs.terListTableRef.queryData(params, (res) => {
            const mediaIdList = this.clickCache && this.clickCache.client_id.indexOf(',')?this.clickCache.client_id.split(','): [this.clickCache.client_id]
            const checkRows = []
            mediaIdList.forEach((item) => {
              const findIndex = res.findIndex((result) => {
                return item == result.id
              })

              if(findIndex !== -1) {
                checkRows.push(res[findIndex])
              }
            })
            if(mediaIdList.length > 0) {
              this.$refs.terListTableRef.toggleRowSelectionMethods(checkRows)
            }
          })
        })
      } else if(val == 3) {
        if(this.clickCache && this.clickCache.quickly_id) {
          this.operateName = this.clickCache.quickly_name
        }
      }
    }
  },
  mounted() {
    this.mediaTypeOptions = []
    Object.keys(suffixFileMapStr).forEach((item) => {
      const tmp = {
        value: item,
        label: suffixFileMapStr[item]
      }
      this.mediaTypeOptions.push(tmp)
    })
    this.getList()
    // this.getAllFileTree()
  },
  methods: {
    getFileTypeImage(row) {
      let tmp = ''
      if(row.media_type == 1) {
        tmp = require('./images/video.png');
      } else if(row.media_type == 2) {
        tmp = require('./images/image.png');
      } else if(row.media_type == 3) {
        const suffixMap = {
          doc: require('./images/word.png'),
          xls: require('./images/excel.png'),
          ppt: require('./images/ppt.png'),
          pdf: require('./images/pdf.png'),
          txt: require('./images/txt.png'),
        }
        Object.keys(suffixMap).forEach((key) => {
          if(row.media_suffix && row.media_suffix.indexOf(key) !== -1) {
            tmp = suffixMap[key]
          }
        })
      } else if(row.media_type == 4) {
        tmp = require('./images/exe.png');
      } else if(row.media_type == 5) {
        tmp = require('./images/web.png');
      } else if(row.media_type == 6) {
        tmp = require('./images/destop.png');
      } else if(row.media_type == 7) {
        tmp = require('./images/other.png');
      } else if(row.media_type == 8) {
        tmp = require('./images/program.png');
      } else if(row.media_type == 9) {
        tmp = require('./images/video.png');
      }
      return tmp
    },
    getMediaList() {
      console.log('searchFileParams ---', this.searchFileParams)
      this.$refs.quickOperateContentRef.queryData({...this.searchFileParams}, (res) => {
        const mediaIdList = this.clickCache && this.clickCache.media_id.indexOf(',')?this.clickCache.media_id.split(','): [this.clickCache.media_id]
        const checkRows = []
        mediaIdList.forEach((item) => {
          const findIndex = res.findIndex((result) => {
            return item == result.id
          })

          if(findIndex !== -1) {
            checkRows.push(res[findIndex])
          }

          if(this.historySelection.length > 0) {
            this.historySelection.forEach((item) => {
              checkRows.push(item)
            })
          }
        })
        if(mediaIdList.length > 0) {
          this.$refs.quickOperateContentRef.toggleRowSelectionMethods(checkRows)
        }
      })
    },
    changeMediaType(val) {
      this.mutiSelectFileList.forEach((item) => {
        const findIndex = this.historySelection.findIndex((result) => {
          return result.id == item.id
        })
        if(findIndex === -1) {
          this.historySelection.push(item)
        }
      })
      console.log('historySelection ---', this.historySelection)
      this.$refs.quickOperateContentRef.resetPageNo()
      this.searchFileParams.mediaType = val
      this.getMediaList()
    },
    sendFile(row) {
      const params = {
        quicklyIds: [row.quickly_id]
      }

      service.quicklyListSend(params).then(() => {
        this.$message.success('分发成功')
      })
    },
    sendFileBySelection() {
      let clientIds = []
      let mediaIds = []
      let quicklyId = []
      if(this.mutiDelList.length === 0) {
        this.$message.error('请选择同步快捷列表')
        return
      }

      this.mutiDelList.forEach((item) => {
        quicklyId.push(item.quickly_id)
      })

      const params = {
        quicklyIds: quicklyId.slice()
      }

      service.quicklyListSend(params).then(() => {
        this.$message.success('发送成功')
        this.mutiDelList = []
        this.$refs.quickOperateContentRef.clearSelectionMethods()
      })
    },
    mutiDelHandler() {
      if(this.mutiDelList.length === 0) {
        this.$message.error('请选择删除的分发内容')
        return
      }
      this.statusProp = true
    },
    editFile(row) {
      this.step = 1
      this.isShowUploadDialog = true
      this.clickCache = row
      this.selectedMediaIds = row.media_id
    },
    cancelHandler() {
      this.statusProp = false
      this.clickCache = {}
      this.mutiDelList = []
    },
    changeQickListRowMethods(row) {
      this.mutiDelList = [...row]
    },
    confirmDelMethods() {
      if(this.mutiDelList.length > 0) {
        const params = {
          ids: []
        }
        this.mutiDelList.forEach((item) => {
          params.ids.push(item.quickly_id)
        })

        service.quicklyDel(params.ids).then(() => {
          this.$message.success('删除成功')
          this.getList()
          this.statusProp = false
          this.mutiDelList = []
          this.$refs.quickOperateRef.clearSelectionMethods()
        })
      } else {
        const params = {
          ids: [this.clickCache.quickly_id]
        }
        service.quicklyDel(params.ids).then(() => {
          this.$message.success('删除成功')
          this.getList()
          this.statusProp = false
          this.clickCache = {}
        })
      }
    },
    showDelWarn(row) {
      this.clickCache = Object.assign({}, row)
      this.statusProp = true
    },
    confirmSavePrevStep() {
      this.step = this.step - 1
    },
    confirmSaveStep() {
      if(this.step === 1 && this.mutiSelectFileList.length === 0) {
        this.$message.error('请选择要分发的文件')
        return
      } else if(this.step === 2 && this.mutiTerList.length === 0) {
        this.$message.error('请选择分发的终端')
        return
      } else if(this.step === 3) {
        let terTmp = []
        this.mutiTerList.forEach((item) => {
          terTmp.push(item.id)
        })
        let mediaTmp = []
        this.mutiSelectFileList.forEach((item) => {
          mediaTmp.push(item)
        })
        const params = {
          clientIds: terTmp.slice(),
          mediaIds: mediaTmp.slice(),
          quicklyName: this.operateName
        }
        if(this.clickCache && this.clickCache.quickly_id) {
          params.quicklyId = this.clickCache.quickly_id
        }
        service.quicklySave(params).then(() => {
          this.$message.success('保存成功')
          this.getList()
          this.handleClose()
        })
        return
      }
      this.step = this.step + 1
    },
    changeFileRowMethods(row) {
      console.log('row ---', row)
      this.mutiSelectFileList = JSON.parse(JSON.stringify(row))

    },
    changeRowMethods(row) {
      this.mutiTerList = JSON.parse(JSON.stringify(row))
    },
    handleClose() {
      this.isShowUploadDialog = false
      this.searchMedia.type = ''
      this.searchFileParams = {
        name: '',
        parentId: 0,
        child: true,
        audit: 1
        // fileType: 2
      }
      this.mutiTerList = []
      this.clickCache = {}
      this.mutiSelectFileList = []
      this.step = 1
    },
    getAllFileTree() {
      const params = {
        page: 1,
        pageSize: 200000000
      }
      service.getFileList(params).then((res) => {
        console.log('res.data ---', res)
        // 根据parentId生成树
        let tmpList = []
        res.data.records.forEach((item) => {
          if(item.parent_id == 0) {
            let tmp = {
              label: item.media_name,
              id: item.id,
              parentId: item.parent_id,
              mediaType: item.media_type,
              children: []
            }

            tmpList.push(tmp)
          } else {
            const findIndex = tmpList.findIndex((result) => {
              return result.id == item.parent_id
            })
            if(findIndex !== -1) {
              console.log('tmpList[findIndex] ---', tmpList[findIndex])
              let child = {
                label: item.media_name,
                id: item.id,
                parentId: item.parent_id,
                mediaType: item.media_type,
                children: []
              }
              tmpList[findIndex].children.push(child)
            }
          }
        })
        this.treeData = tmpList.slice()
        console.log('this.treeData ---', this.treeData)
      })
    },
    formatTreeData(res) {

    },
    getList() {
      const params = Object.assign({}, this.searchObj)
      this.$refs.quickOperateRef.queryData(params)
    },
    queryMethods() {
      console.log('开始搜索 ---')
      this.searchObj.page = 1
      this.getList()
    },
    startUploadFile() {
      this.isShowUploadDialog = true
      this.$nextTick(() => {
        this.$refs.quickOperateContentRef.resetPageNo()
        this.$refs.quickOperateContentRef.queryData({...this.searchFileParams})
      })
    },
    closeUpload() {
      this.isShowUploadDialog = false
    }
  }
}
</script>

<style scoped lang="scss">
  .video-page{
    padding: 15px;
    background: white;

    .terminal-search-title{

    }

    .commonTable{
      margin-top: 15px;
    }
  }
  .steps{
    width: 260px;
    margin: 0 auto;
  }
  ::v-deep .el-dialog__body{
    padding: 20px;
  }

  ::v-deep .el-table [class*=el-table__row--level] .el-table__expand-icon {
    float: left;
    line-height: 24px;
  }

  ::v-deep .el-table__indent,::v-deep .el-table__placeholder{
    float: left;
    height: 1px;
  }
</style>
